﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using AutoUpdate.Models;
using Microsoft.EntityFrameworkCore;

namespace AutoUpdate.DAL
{
    public class BaseDAL<T> where T : class, new()
    {
        private DbContext db = ContextFactory.Create();

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="t"></param>
        public void Add(T t)
        {
            db.Set<T>().Add(t);
        }


        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="t"></param>
        public void Update(T t)
        {
            db.Set<T>().Update(t);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="t"></param>
        public void Delete(T t)
        {
            db.Set<T>().Remove(t);
        }

        /// <summary>
        /// 根据条件返回
        /// </summary>
        /// <param name="whereLambda"></param>
        /// <returns></returns>
        public IQueryable<T> GetModel(Expression<Func<T, bool>> whereLambda)
        {
            return db.Set<T>().Where(whereLambda);
        }
        
        /// <summary>
        /// 根据条件分页返回
        /// </summary>
        /// <typeparam name="type"></typeparam>
        /// <param name="pageSize"></param>
        /// <param name="PageIndex"></param>
        /// <param name="isAsc"></param>
        /// <param name="OrderbyLambda"></param>
        /// <param name="whereLambda"></param>
        /// <returns></returns>
        public IQueryable<T> GetModelByPage<type>(int pageSize,int PageIndex,bool isAsc,Expression<Func<T,type>> OrderbyLambda,Expression<Func<T,bool>> whereLambda)
        {
            if (isAsc)
            {
                return db.Set<T>().Where(whereLambda).OrderBy(OrderbyLambda).Skip((PageIndex - 1) * pageSize).Take(pageSize);

            }
            else
            {
                return db.Set<T>().Where(whereLambda).OrderByDescending(OrderbyLambda).Skip((PageIndex - 1) * pageSize).Take(pageSize);
            }
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <returns></returns>
        public bool SaveChanges()
        {
            return db.SaveChanges() > 0;
        }
    }
}
